// 用户状态管理

import { defineStore } from 'pinia'
import type { User, Address } from '@/types/mall'
import { STORAGE_KEYS } from '@/constants/mall'

interface UserState {
  user: User | null
  token: string | null
  refreshToken: string | null
  isLoggedIn: boolean
  loading: boolean
  addresses: Address[]
  defaultAddress: Address | null
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    user: null,
    token: null,
    refreshToken: null,
    isLoggedIn: false,
    loading: false,
    addresses: [],
    defaultAddress: null,
  }),

  getters: {
    // 用户头像
    userAvatar(): string {
      return this.user?.avatar || 'https://via.placeholder.com/100x100?text=头像'
    },

    // 用户昵称
    userNickname(): string {
      return this.user?.nickname || this.user?.username || '用户'
    },

    // 用户等级
    userLevel(): number {
      return this.user?.level || 1
    },

    // 用户积分
    userPoints(): number {
      return this.user?.points || 0
    },

    // 用户余额
    userBalance(): number {
      return this.user?.balance || 0
    },

    // 是否有默认地址
    hasDefaultAddress(): boolean {
      return !!this.defaultAddress
    },
  },

  actions: {
    // 初始化用户信息
    async initUser() {
      try {
        const token = uni.getStorageSync(STORAGE_KEYS.ACCESS_TOKEN)
        const refreshToken = uni.getStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
        const userInfo = uni.getStorageSync(STORAGE_KEYS.USER_INFO)

        if (token && userInfo) {
          this.token = token
          this.refreshToken = refreshToken
          this.user = JSON.parse(userInfo)
          this.isLoggedIn = true
          
          // 获取用户最新信息
          await this.getUserInfo()
        }
      } catch (error) {
        console.error('Failed to init user:', error)
        this.clearUserData()
      }
    },

    // 用户登录
    async login(username: string, password: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用登录API
        // const response = await api.user.login({ username, password })
        // const { user, token, refreshToken } = response.data

        // 模拟登录响应
        const mockResponse = {
          user: {
            id: '1',
            username,
            nickname: '测试用户',
            avatar: 'https://via.placeholder.com/100x100?text=头像',
            phone: '13800138000',
            email: 'test@example.com',
            gender: 'unknown' as const,
            level: 1,
            points: 100,
            balance: 0,
            status: 'active' as const,
            createdAt: new Date().toISOString(),
            updatedAt: new Date().toISOString(),
          },
          token: 'mock_token_' + Date.now(),
          refreshToken: 'mock_refresh_token_' + Date.now(),
        }

        this.setUserData(mockResponse.user, mockResponse.token, mockResponse.refreshToken)
        
        uni.showToast({ title: '登录成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Login failed:', error)
        uni.showToast({ title: '登录失败，请重试', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 用户注册
    async register(userData: {
      username: string
      password: string
      phone?: string
      email?: string
    }): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用注册API
        // const response = await api.user.register(userData)
        
        uni.showToast({ title: '注册成功，请登录', icon: 'success' })
        return true
      } catch (error) {
        console.error('Register failed:', error)
        uni.showToast({ title: '注册失败，请重试', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 用户登出
    async logout(): Promise<boolean> {
      try {
        // TODO: 调用登出API
        // await api.user.logout()
        
        this.clearUserData()
        uni.showToast({ title: '已退出登录', icon: 'success' })
        return true
      } catch (error) {
        console.error('Logout failed:', error)
        this.clearUserData()
        return false
      }
    },

    // 获取用户信息
    async getUserInfo(): Promise<boolean> {
      try {
        if (!this.token) return false

        // TODO: 调用获取用户信息API
        // const response = await api.user.getUserInfo()
        // this.user = response.data
        
        this.saveUserInfo()
        return true
      } catch (error) {
        console.error('Failed to get user info:', error)
        return false
      }
    },

    // 更新用户信息
    async updateUserInfo(userData: Partial<User>): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用更新用户信息API
        // const response = await api.user.updateUserInfo(userData)
        // this.user = response.data

        if (this.user) {
          Object.assign(this.user, userData)
          this.saveUserInfo()
        }

        uni.showToast({ title: '更新成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to update user info:', error)
        uni.showToast({ title: '更新失败，请重试', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 修改密码
    async changePassword(oldPassword: string, newPassword: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用修改密码API
        // await api.user.changePassword({ oldPassword, newPassword })

        uni.showToast({ title: '密码修改成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to change password:', error)
        uni.showToast({ title: '密码修改失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 上传头像
    async uploadAvatar(filePath: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用上传头像API
        // const response = await api.user.uploadAvatar(filePath)
        // if (this.user) {
        //   this.user.avatar = response.data.avatar
        //   this.saveUserInfo()
        // }

        uni.showToast({ title: '头像上传成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to upload avatar:', error)
        uni.showToast({ title: '头像上传失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 获取地址列表
    async getAddresses(): Promise<boolean> {
      try {
        // TODO: 调用获取地址列表API
        // const response = await api.address.getAddressList()
        // this.addresses = response.data

        // 设置默认地址
        this.defaultAddress = this.addresses.find(addr => addr.isDefault) || null

        return true
      } catch (error) {
        console.error('Failed to get addresses:', error)
        return false
      }
    },

    // 添加地址
    async addAddress(addressData: Omit<Address, 'id' | 'userId' | 'createdAt' | 'updatedAt'>): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用添加地址API
        // const response = await api.address.createAddress(addressData)
        // this.addresses.push(response.data)

        // 如果是默认地址，更新defaultAddress
        // if (addressData.isDefault) {
        //   this.defaultAddress = response.data
        // }

        uni.showToast({ title: '地址添加成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to add address:', error)
        uni.showToast({ title: '地址添加失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 更新地址
    async updateAddress(addressId: string, addressData: Partial<Address>): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用更新地址API
        // const response = await api.address.updateAddress(addressId, addressData)

        // 更新本地地址数据
        const index = this.addresses.findIndex(addr => addr.id === addressId)
        if (index >= 0) {
          Object.assign(this.addresses[index], addressData)
          
          // 如果是默认地址，更新defaultAddress
          if (addressData.isDefault) {
            this.defaultAddress = this.addresses[index]
          }
        }

        uni.showToast({ title: '地址更新成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to update address:', error)
        uni.showToast({ title: '地址更新失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 删除地址
    async deleteAddress(addressId: string): Promise<boolean> {
      try {
        this.loading = true

        // TODO: 调用删除地址API
        // await api.address.deleteAddress(addressId)

        // 删除本地地址数据
        const index = this.addresses.findIndex(addr => addr.id === addressId)
        if (index >= 0) {
          const deletedAddress = this.addresses[index]
          this.addresses.splice(index, 1)
          
          // 如果删除的是默认地址，重新设置默认地址
          if (deletedAddress.isDefault) {
            this.defaultAddress = this.addresses.find(addr => addr.isDefault) || null
          }
        }

        uni.showToast({ title: '地址删除成功', icon: 'success' })
        return true
      } catch (error) {
        console.error('Failed to delete address:', error)
        uni.showToast({ title: '地址删除失败', icon: 'none' })
        return false
      } finally {
        this.loading = false
      }
    },

    // 设置默认地址
    async setDefaultAddress(addressId: string): Promise<boolean> {
      try {
        // TODO: 调用设置默认地址API
        // await api.address.setDefaultAddress(addressId)

        // 更新本地数据
        this.addresses.forEach(addr => {
          addr.isDefault = addr.id === addressId
        })
        this.defaultAddress = this.addresses.find(addr => addr.id === addressId) || null

        return true
      } catch (error) {
        console.error('Failed to set default address:', error)
        return false
      }
    },

    // 设置用户数据
    setUserData(user: User, token: string, refreshToken?: string) {
      this.user = user
      this.token = token
      this.refreshToken = refreshToken || null
      this.isLoggedIn = true
      
      this.saveUserInfo()
      this.saveTokens()
    },

    // 清除用户数据
    clearUserData() {
      this.user = null
      this.token = null
      this.refreshToken = null
      this.isLoggedIn = false
      this.addresses = []
      this.defaultAddress = null
      
      uni.removeStorageSync(STORAGE_KEYS.USER_INFO)
      uni.removeStorageSync(STORAGE_KEYS.ACCESS_TOKEN)
      uni.removeStorageSync(STORAGE_KEYS.REFRESH_TOKEN)
    },

    // 保存用户信息到本地
    saveUserInfo() {
      if (this.user) {
        uni.setStorageSync(STORAGE_KEYS.USER_INFO, JSON.stringify(this.user))
      }
    },

    // 保存令牌到本地
    saveTokens() {
      if (this.token) {
        uni.setStorageSync(STORAGE_KEYS.ACCESS_TOKEN, this.token)
      }
      if (this.refreshToken) {
        uni.setStorageSync(STORAGE_KEYS.REFRESH_TOKEN, this.refreshToken)
      }
    },

    // 刷新令牌
    async refreshAccessToken(): Promise<boolean> {
      try {
        if (!this.refreshToken) return false

        // TODO: 调用刷新令牌API
        // const response = await api.user.refreshToken(this.refreshToken)
        // this.token = response.data.token
        // this.refreshToken = response.data.refreshToken
        
        this.saveTokens()
        return true
      } catch (error) {
        console.error('Failed to refresh token:', error)
        this.clearUserData()
        return false
      }
    },
  },

  // 开启持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: STORAGE_KEYS.USER_INFO,
        storage: {
          getItem: (key: string) => uni.getStorageSync(key),
          setItem: (key: string, value: string) => uni.setStorageSync(key, value),
          removeItem: (key: string) => uni.removeStorageSync(key),
        },
        paths: ['user', 'isLoggedIn'],
      },
      {
        key: STORAGE_KEYS.ACCESS_TOKEN,
        storage: {
          getItem: (key: string) => uni.getStorageSync(key),
          setItem: (key: string, value: string) => uni.setStorageSync(key, value),
          removeItem: (key: string) => uni.removeStorageSync(key),
        },
        paths: ['token', 'refreshToken'],
      },
    ],
  },
})